import tkinter as tk
from scitk.app.sciapp import SciApp
from tkinter import ttk
def extend_plgs(plg):
    if isinstance(plg, tuple):
        return (plg[0].title, extend_plgs(plg[1]))
    elif isinstance(plg, list):
        return [extend_plgs(i) for i in plg]
    elif isinstance(plg, str): return plg
    else: return (plg.title, plg)

def extend_tols(tol):
    if isinstance(tol, tuple) and isinstance(tol[1], list):
        return (tol[0].title, extend_tols(tol[1]))
    elif isinstance(tol, tuple) and isinstance(tol[1], str):
        return (tol[1], tol[0])
    elif isinstance(tol, list): return [extend_tols(i) for i in tol]

def build_widgets(path, err=False):
    root = err in (True, False)
    if root: sta, err = err, []
    subtree = []
    cont = os.listdir(os.path.join(root_dir, path))
    for i in cont:
        subp = os.path.join(path,i)
        if root and os.path.isdir(os.path.join(root_dir, subp)):
            sub = build_widgets(subp, err)
            if len(sub)!=0:subtree.append(sub)
        elif not root:
            if i[len(i)-7:] in ('_wgt.py', 'wgts.py'):
                subtree.append(i[:-3])
                #print('====', subtree)
    if len(subtree)==0:return []
    rpath = path.replace('/', '.').replace('\\','.')
    #rpath = rpath[rpath.index('imagepy.'):]
    pg = __import__('imagepy.' + rpath,'','',[''])
    pg.title = os.path.basename(path)
    if hasattr(pg, 'catlog'):
        subtree = sort_widgets(pg.catlog, subtree)
    if not root:
        subtree = extend_widgets(path, subtree, err)  
    elif sta and len(err)>0: 
        IPy.write('widgets not loaded:')
        for i in err: IPy.write('>>> %-50s%-20s%s'%i)
    return (pg, subtree)


def extend_wgts(wgt):
    if isinstance(wgt, tuple) and isinstance(wgt[1], list):
        return (wgt[0].title, extend_wgts(wgt[1]))
    elif isinstance(wgt, list): return [extend_wgts(i) for i in wgt]
    else: return (wgt.title, wgt)

class TestFrame(ttk.Frame):
    def __init__(self,parent):
        super().__init__(parent)
        self.b=ttk.Button(self,text='哈哈哈哈')
        self.b.pack()

def start():
    from skimage.data import camera, astronaut

    app = tk.Tk()

    frame = SciApp(app)
##    frame.load_menu(extend_plgs(loader.build_plugins('menus')))
##    frame.load_tool(extend_tols(loader.build_tools('tools')), 'Transform')
    frame.load_widget( ('widgets', [('panels', [('A', TestFrame), ('B', ttk.Frame)]),
        ('panels2', [('A', ttk.Frame), ('B', ttk.Frame)])]))
    frame.pack(expand=1,fill=tk.BOTH)
##    frame.Fit()
    #frame.show_img([camera()], 'camera')
    #frame.show_img([astronaut()], 'astronaut')

    app.mainloop()
if __name__=='__main__':
    start()